package com.dlc.shop.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dlc.shop.common.bean.QuickCdek;
import com.dlc.shop.config.ShopConfig;
import com.dlc.shop.service.CdekAuthTokenService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


@Service
@AllArgsConstructor
public class CdekAuthTokenServiceImpl implements CdekAuthTokenService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final ShopConfig shopConfig;
    @Override
    @Cacheable(cacheNames = "cdek_auth_token", unless = "#result == null")
    public String authToken() {
        // 构建POST请求
        QuickCdek cdekQuick = shopConfig.getCdekQuick();
        String url = cdekQuick.getUrl()+"?grant_type="+cdekQuick.getGrantType()+"&client_id="+cdekQuick.getClientId()+"&client_secret="+cdekQuick.getClientSecret();
        HttpRequest request = HttpRequest.post(url)
                .header("Content-Type", "x-www-form-urlencoded");
        //.body(JSONObject.toJSONString(params));// 设置请求头
        // 设置请求体，这里是一个JSON字符串
        // 发送请求，并接收响应
        HttpResponse response = request.execute();
        // 打印响应的内容
        logger.info(response.body());
        JSONObject jsonObject = JSON.parseObject(response.body());

        if (jsonObject.get("error") != null){
            logger.info(jsonObject.get("error_description").toString());
            return null ;
        }else{
            return jsonObject.get("access_token").toString();
        }
    }

}
